//
//  GActivityIndicatorView.m
//  iphone51buy
//
//  Created by icson apple on 12-5-29.
//  Copyright (c) 2012年 icson. All rights reserved.
//

#import "GActivityIndicatorView.h"

@implementation GActivityIndicatorView

- (void)dealloc
{
    [foreImageView release];
    [orangeView release];
    [super dealloc];
}

- (void)internalInit
{
    @autoreleasepool {
        CGRect frame = self.bounds;
        foreImageView = [[UIImageView alloc] initWithFrame:frame];
        [foreImageView setImage:[UIImage imageNamed:@"loading_bg.png"]];
        [self insertSubview: foreImageView atIndex: 2];
        
        orangeView = [[UIView alloc] initWithFrame:frame];
        [orangeView setBackgroundColor: [UIColor orangeColor]];
        [self insertSubview: orangeView atIndex: 0];
        
        isAnimating = NO;
        
        [self setClipsToBounds: YES];
    }
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self internalInit];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self internalInit];
    }
    return self;        
}

- (void)layoutSubviews
{
	[super layoutSubviews];
	
	[foreImageView setFrame: CGRectMake(0.0, 0.0, self.frame.size.width, self.frame.size.height)];
	[orangeView setFrame: CGRectMake(0.0, 0.0, self.frame.size.width, self.frame.size.height)];

	if (isAnimating && !blueView) {
		[self startAnimating];
	}
}

- (void)doAnimation
{
	CATransition *trans = [CATransition animation];
	trans.type = kCATransitionPush;
	trans.subtype = kCATransitionFromBottom;
	trans.duration = 0.8;
	trans.delegate = self;
	trans.repeatCount = HUGE_VALF;
	[blueView.layer addAnimation: trans forKey: kCATransition];

	[blueView setFrame: CGRectMake(0.0, 0.0, self.frame.size.width, self.frame.size.height)];
	[UIView commitAnimations];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
	[blueView removeFromSuperview]; blueView = nil;
}

- (void)startAnimating
{
	if (blueView) {
		return;
	}

	isAnimating = YES;
	blueView = [[UIView alloc] initWithFrame: CGRectMake(0.0, 0.0, self.frame.size.width, 0.0)];
	[blueView setBackgroundColor: [UIColor blueColor]];
	[self insertSubview: blueView atIndex: 1];
    [blueView release];
	[self doAnimation];
}

- (void)stopAnimating
{
	isAnimating = NO;
	[blueView removeFromSuperview]; blueView = nil;
}

- (BOOL)isAnimating
{
	return isAnimating;
}

@end
